# Create your views here.
from sys import exc_info
from traceback import format_exception
from items.models import item_def, item_instance
from django.http import Http404, HttpResponse, HttpResponseNotAllowed
from django.shortcuts import render_to_response
from items.submission import process_xml_item, update_statistics

# This view serves the page for details of a single item definition.
def item_detail(request, item_id):
    item = item_def.get_by_id(int(item_id))
    if (item == None):
        raise Http404
    else:
        return render_to_response('items/item_detail.html', {'item_def': item})
    
# This view provides all the details of a particular item instance, including those in the item definition.
def inst_detail(request, item_id, inst_id):
    item = item_def.get_by_id(int(item_id))
    if (item == None):
        return HttpResponse("Item with item_id = " + str(item_id) + " not found!")
    else:
        inst = item_instance.get_by_id(int(inst_id))
        if (inst == None):
            return HttpResponse("Instance with inst_id = " + str(inst_id) + " not found!")
        else:
            context = {'item_def': item, 'item_inst': inst}
            return render_to_response('items/instance_detail.html', context)

# This view lists all instances of a particular item definition.
def item_inst_list(request, item_id):
    item = item_def.get_by_id(int(item_id))
    if (item == None):
        return HttpResponse("Item with item_id = " + str(item_id) + " not found!")
    else:
        query = item_instance.all()
        query.filter('parentitem', item.key())
        query.order('level')
        all_insts = []
        for inst in query:
            all_insts.append(inst)
        return render_to_response('items/instance_list.html', {'all_insts': all_insts})
    
# This view is a simple RESTful interface for item submission.  
# I did not choose to use one of the available RESTful APIs 
# due to GAE compatibility issues and the relative simplicity
# of what I needed to do.

def xml_item_submit(request):

    # Only accepts POST requests since URLs are determined by the item key values.
    if request.method != 'POST':
        return HttpResponse(status = 501)

    try:
        new_item_inst = process_xml_item(request)
        query = item_def.all()
        query.filter('itemname', new_item_inst.itemname)
        current_item_def = query.get()
        
        if current_item_def == None:
            current_item_def = item_def()
            current_item_def.itemname = new_item_inst.itemname

        update_statistics(current_item_def, new_item_inst)
        current_item_def.put()
        
        item_key = current_item_def.key()
        new_item_inst.parentitem = item_key
        new_item_inst.put()
            
        return HttpResponse('OK\n'
                            +'\n'
                            +str(item_key)+'\n'
                            +str(new_item_inst.key())+'\n')

    except:
        exc_type, exc_value, exc_tb = exc_info()
        exc_str = repr(format_exception(exc_type, exc_value, exc_tb))
        return HttpResponse(exc_str)



    


    



        
